package org.eclipse.refactoring.localvariable;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;

public class PrefixRefactorAction implements IWorkbenchWindowActionDelegate {

	private ICompilationUnit mICompilationUnit = null;
	private IPackageFragment mIPackageFragment = null;

	private IWorkbenchWindow mWindow = null;

	@Override
	public void dispose() {
		// Do nothing
	}

	@Override
	public void init(IWorkbenchWindow window) {
		mWindow = window;
	}

	@Override
	public void run(IAction action) {
		if (mICompilationUnit != null && mWindow != null) {
			PrefixRefactorRefactoring refactoring = new PrefixRefactorRefactoring();
			refactoring.setCompilationUnit(mICompilationUnit);
			run(new PrefixRefactorWizard(refactoring, "Prefix Local Variables"),
					mWindow.getShell(), "Prefix Local Variables");
		} else if (mIPackageFragment != null && mWindow != null) {
			PrefixRefactorRefactoring refactoring = new PrefixRefactorRefactoring();
			refactoring.setPackageFragment(mIPackageFragment);
			run(new PrefixRefactorWizard(refactoring, "Prefix Local Variables"),
					mWindow.getShell(), "Prefix Local Variables");
		}
	}

	public void run(RefactoringWizard wizard, Shell parent, String dialogTitle) {
		try {
			RefactoringWizardOpenOperation lOperation = new RefactoringWizardOpenOperation(
					wizard);
			lOperation.run(parent, dialogTitle);
		} catch (InterruptedException exception) {
			// Do nothing
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		mICompilationUnit = null;
		mIPackageFragment = null;

		if (selection instanceof IStructuredSelection) {
			IStructuredSelection extended = (IStructuredSelection) selection;
			Object[] elements = extended.toArray();
			if (elements.length == 1) {
				if (elements[0] instanceof ICompilationUnit) {
					mICompilationUnit = (ICompilationUnit) elements[0];
				} else if (elements[0] instanceof IPackageFragment) {
					mIPackageFragment = (IPackageFragment) elements[0];
				}
			}
		}
		try {
			boolean lIsEnabled = mICompilationUnit != null
					&& mICompilationUnit.exists()
					&& mICompilationUnit.isStructureKnown();
			lIsEnabled |= mIPackageFragment != null
					&& mIPackageFragment.exists()
					&& mIPackageFragment.isStructureKnown();
			action.setEnabled(lIsEnabled);
		} catch (JavaModelException exception) {
			action.setEnabled(false);
		}
	}
}